﻿using LBSoft.Common.DotNetBean;
using LBSoft.Common.DotNetCode;
using LBSoft.Common.DotNetExt;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LBSoft.Business.DAL
{
    public class Permission_Dal
    {
        Common_Dal systemidao = new Common_Dal();
        LogHelper log = new LogHelper();

        /// <summary>
        /// 获取用户角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public string GetUserRolesId(string userId)
        {
            string roleGUID = systemidao.ExecuteScalar($"SELECT TOP 1 RoleGUID FROM dbo.SYS_UserInfo WHERE GUID='{userId}'").ToString2();
            return roleGUID;
        }

        public DataTable GetMenu(string rolesId, string userId, int userType)
        {
            string roleWhere = string.Empty;
            string userWhere = string.Empty;

            if (userType != 1)
            {
                roleWhere = $" AND CHARINDEX(rr.RoleGUID,'{rolesId}')>0 ";
                userWhere = $" AND ur.UserGUID='{userId}' ";
            }

            DataTable dtMenu = systemidao.GetDataTableBySQL(new StringBuilder($@"
            SELECT m.GUID,m.ParentId,m.MenuName,m.MenuIcon,m.MenuType,m.NavigateUrl,m.ButtonType,m.Sort FROM (
	            SELECT m.GUID,m.ParentId,m.MenuName,m.MenuIcon,m.MenuType,m.NavigateUrl,m.ButtonType,m.Sort,'角色权限' RightType  FROM dbo.SYS_Menu m
	            LEFT JOIN dbo.SYS_RoleRight rr ON rr.MenuGUID=m.GUID
	            WHERE 1=1 AND m.IsDelete=0 {roleWhere}
	            UNION ALL
	            SELECT m.GUID,m.ParentId,m.MenuName,m.MenuIcon,m.MenuType,m.NavigateUrl,m.ButtonType,m.Sort,'用户权限' RightType FROM dbo.SYS_Menu m
	            LEFT JOIN dbo.SYS_UserRight ur ON ur.MenuGUID=m.GUID
	            WHERE 1=1 AND m.IsDelete=0 {userWhere}
            ) m
            GROUP BY m.GUID,m.ParentId,m.MenuName,m.MenuIcon,m.MenuType,m.NavigateUrl,m.ButtonType,m.Sort
            ORDER BY m.Sort"));

            return dtMenu;
        }

        public string MenuString = string.Empty;
        /// <summary>
        /// 获取菜单
        /// </summary>
        public string GetMenuData()
        {
            try
            {
                int userType = RequestSession.GetSessionUser().UserType;
                string userId = RequestSession.GetSessionUser().UserId;
                string rolesId = GetUserRolesId(userId);

                DataTable dtMenu = GetMenu(rolesId, userId, userType);

                if (dtMenu != null && dtMenu.Rows.Count > 0)
                {
                    DataRow[] drArr = dtMenu.Select("ParentId='0' and MenuType='1'");
                    if (drArr != null && drArr.Length > 0)
                    {
                        foreach (DataRow dr in drArr)
                        {
                            string guid = dr["GUID"].ToString2();
                            string menuName = dr["MenuName"].ToString2();
                            string menuIcon = dr["MenuIcon"].ToString2();
                            string navigateUrl = dr["NavigateUrl"].ToString2();

                            //根据ParentId判断字节点
                            DataRow[] drSubArr = dtMenu.Select($"ParentId='{guid}' and MenuType='1'");
                            if (drSubArr != null && drSubArr.Length > 0)
                            {
                                MenuString += "<li>";
                                MenuString += $"<a href=\"#\"><i class=\"{menuIcon}\"></i><span class=\"nav-label\">{menuName}</span><span class=\"fa arrow\"></span></a>";
                                MenuString += "<ul class=\"nav nav-second-level\">";
                                foreach (DataRow drSub in drSubArr)
                                {
                                    string subGUID = drSub["GUID"].ToString2();
                                    string subMenuName = drSub["MenuName"].ToString2();
                                    string subMenuIcon = drSub["MenuIcon"].ToString2();
                                    string subNavigateUrl = drSub["NavigateUrl"].ToString2();

                                    GetSubMenuString(dtMenu, subGUID, subMenuName, subMenuIcon, subNavigateUrl);
                                }
                                MenuString += "</ul>";
                                MenuString += "</li>";
                            }
                            else
                            {
                                MenuString += $"<li><a class=\"J_menuItem\" href=\"{navigateUrl}\"><i class=\"{menuIcon}\"></i><span class=\"nav-label\">{menuName}</span></a></li>";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.WriteExceptionLog(ex);
            }

            return MenuString;
        }

        /// <summary>
        /// 递归获取二级及以下节点
        /// </summary>
        /// <param name="dtMenu"></param>
        /// <param name="guid"></param>
        /// <param name="menuName"></param>
        /// <param name="menuIcon"></param>
        /// <param name="navigateUrl"></param>
        private void GetSubMenuString(DataTable dtMenu, string guid, string menuName, string menuIcon, string navigateUrl)
        {
            try
            {
                DataRow[] drSubArr = dtMenu.Select($"ParentId='{guid}' and MenuType='1'");
                if (drSubArr != null && drSubArr.Length > 0)
                {
                    MenuString += "<li>";
                    MenuString += $"<a href=\"#\"><i class=\"{menuIcon}\"></i><span class=\"nav-label\">{menuName}</span><span class=\"fa arrow\"></span></a>";
                    MenuString += "<ul class=\"nav nav-third-level\">";
                    foreach (DataRow drSub in drSubArr)
                    {
                        string subGUID = drSub["GUID"].ToString2();
                        string subMenuName = drSub["MenuName"].ToString2();
                        string subMenuIcon = drSub["MenuIcon"].ToString2();
                        string subNavigateUrl = drSub["NavigateUrl"].ToString2();

                        GetSubMenuString(dtMenu, subGUID, subMenuName, subMenuIcon, subNavigateUrl);
                    }
                    MenuString += "</ul>";
                    MenuString += "</li>";
                }
                else
                {
                    MenuString += $"<li><a class=\"J_menuItem\" href=\"{navigateUrl}\"><i class=\"{menuIcon}\"></i><span class=\"nav-label\">{menuName}</span></a></li>";
                }
            }
            catch (Exception ex)
            {
                log.WriteExceptionLog(ex);
            }
        }
    }
}
